$(function () {
    //上传图片
    uploadImg();
    //customerPoolSelectInit();
    getIndividualProvince();

    $('#addIndividualCustomerForm').bootstrapValidator({
        fields: {
            /*customerPoolIdSelect1: {
                validators: {
                    notEmpty: {
                        message: '客户池名称不能为空！不能为空'
                    }
                }
            },*/
            customerName1: {
                validators: {
                    notEmpty: {
                        message: '联系人姓名不能为空'
                    },
                    stringLength: {
                        max: 5,
                        message: '联系人姓名长度不能大于5个字符！'
                    }
                }
            },
            enterpriseExternalPhone1: {
                validators: {
                    notEmpty: {
                        message: '手机号不能为空'
                    },
                   //  regexp: {
                   //      regexp: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                   //      message: '请输入正确的手机号'
                   //  }
                    stringLength:{
                        max:12,
                        message:'请输入正确的联系方式'
                    }
                }
            }
        }
    });
});
// 渲染个人客户省市列表
function getIndividualProvince() {
    let provinceNames = ['<option value="init">请选择省份</option>'];
    $.each(cityJson[0], function(key, value){
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#individualProvince').html(provinceNames.join(''));
    getIndividualCity($('#individualProvince').val());
}
// 根据个人客户获取市
function getIndividualCity(provinceId) {
    $('#individualCity').html('');
    let cityNames = ['<option value="init">请选择城市</option>'];
    if(provinceId && provinceId != 'init'){
        let key = '0,'+provinceId;
        $.each(cityJson[key], function(key, value){
            cityNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#individualCity').html(cityNames.join(''));
    getIndividualOrangin($('#individualProvince').val(), $('#individualCity').val());
}
// 个人客户'切换省'
function changeIndividualProvince() {
    getIndividualCity($('#individualProvince').val());
    getIndividualOrangin($('#individualProvince').val(), $('#individualCity').val());
}
// 个人客户获取区
function getIndividualOrangin(provinceId, cityId) {
    $('#individualCounty').html('');
    let oranginNames = ['<option value="init">请选择区/县</option>'];
    if(provinceId && provinceId != 'init' && cityId && cityId != 'init'){
        let key = '0,'+provinceId+ ',' + cityId;
        $.each(cityJson[key], function(key, value){
            oranginNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#individualCounty').html(oranginNames.join(''));
}
// 个人客户切换城市
function changeIndividualCity() {
    getIndividualOrangin($('#individualProvince').val(), $("#individualCity").val());
}
$(document).keypress(
    function(event){
        if (event.which == '13') {
            event.preventDefault();
        }
    });

function addIndividualCustomer(){
    var formData = new FormData();
    //var customerPoolId = $('#customerPoolIdSelect1').val();//客户池主键
    var customerName = $.trim($('#customerName1').val()); //联系人姓名
    var enterpriseExternalPhone = $.trim($('#enterpriseExternalPhone1').val()); //手机号
    var enterpriseExternalLandline = $.trim($('#enterpriseExternalLandline1').val()); //座机号
    var workplaceName = $.trim($('#workplaceName').val()); //单位名称
    var provinceCode = $('#individualProvince').val();
    var provinceName = $('#individualProvince').find("option:selected").text();
    if (provinceCode == 'init'){//init为请选择，为init时置为空
        provinceCode = '';
        provinceName = ''
    }
    var cityCode= $('#individualCity').val();
    var cityName= $("#individualCity").find("option:selected").text();
    if (cityCode == 'init'){//init为请选择，为init时置为空
        cityCode = '';
        cityName = ''
    }
    var countyCode = $('#individualCounty').val();
    var countyName = $('#individualCounty').find("option:selected").text();
    if (countyCode == 'init'){//init为请选择，为init时置为空
        countyCode = '';
        countyName = ''
    }
    //var currentStatus = 1;//目前状态---0: 未领取; 1: 已领取(我领取的客户);2: 已分配(分配给我的客户);3: 自建客户(用户模块我自建的客户);
    //获取选择文件
    var file = document.getElementById("customerPic1").files[0];
    // 验证表单
    var bootstrapValidator = $("#addIndividualCustomerForm").data('bootstrapValidator');

    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }


    //客户池名称为空判断
    /*if(!customerPoolId){
        $.alert("客户池名称不能为空！");
        return;
    }*/
    //联系人姓名为空判断
    /*if(!customerName){
        $.alert("联系人姓名不能为空！");
        return;
    } else if (customerName.length > 40) {
        $.alert("联系人姓名长度不能大于40个字！");
        return;
    }*/
    //手机号
    /*let phoneReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
    if (!phoneReg.test(enterpriseExternalPhone)) {
        $.alert("手机号不存在！");
        return;
    } else if (enterpriseExternalPhone.length > 20) {
        $.alert("手机号长度不能大于20个字！");
        return;
    }*/
    //座机号
    let regexp = /(^(\d{2,4}[-_－—]?)?\d{3,8}([-_－—]?\d{3,8})?([-_－—]?\d{1,7})?$)|(^0?1[35]\d{9}$)/;
    if(enterpriseExternalLandline){
        if (!regexp.test(enterpriseExternalLandline)) {
            $.alert("请输入正确的座机号！");
            return;
        } else if (enterpriseExternalLandline.length > 20) {
            $.alert("座机号长度不能大于20个字！");
            return;
        }
    }
    //单位名称
    if (workplaceName.length > 255) {
        $.alert("单位名称长度不能大于255个字！");
        return;
    }

    formData.append("customerName",customerName);
    formData.append("enterpriseExternalPhone",enterpriseExternalPhone);
    formData.append("enterpriseExternalLandline",enterpriseExternalLandline);
    formData.append("workplaceName",workplaceName);
    //formData.append("customerPoolId",customerPoolId);
    formData.append("provinceCode",provinceCode);
    formData.append("provinceName",provinceName);
    formData.append("cityCode",cityCode);
    formData.append("cityName",cityName);
    formData.append("countyCode",countyCode);
    formData.append("countyName",countyName);
    formData.append("file",file);

    $.ajax({
        url: '/customerController/addIndividualCustomer',
        type: 'POST',
        data: formData,
        contentType : false,
        processData : false,
        cache : false,
        success: (function (data) {
            if (data.data == "C00000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("我的客户","/front/customerManager/myCustomerPool");
                                // 提交完表单，重新加载相关table列表页面
                                refreshActivePane('/front/customerManager/myCustomerPool');
                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if (data.data == "C00001") {
                $.alert("超出客户池容量！");
            } else if (data.data == "C00002") {
                $.alert("手机号已存在！");
            } else if (data.data == "C00003") {
                $.alert("联系人已存在！");
            } else if (data.data == "C00004") {
                $.alert("您所属公司对应的全国公有池不存在，请联系管理员！");
            } else if (data.data == "C00005") {
                $.alert("超出客户容量！");
            } else if (data.data == "C00006") {
                $.alert("联系人姓名不能为空且长度不能大于5个字符！");
            } else {
                $.alert("保存失败！");
            }
        }),
        error: (function () {
            $.alert("保存异常！");
        })
    });
}

function cancelAddIndividualCustomer(){
    window.location.reload();
}

/**
 * 初始化客户池名称下拉
 */
function customerPoolSelectInit(){
    $.ajax({
        type: 'get',
        url: '/customer/selectEnableCustomerPoolName',
        success: function (data) {
            let customerPoolList = data.data;
            let customerPoolOptionStr = "";
            for (let index in customerPoolList) {
                let jsonObj = customerPoolList[index];
                customerPoolOptionStr += "<option value=\"" + jsonObj.customerPoolId + "\">" + jsonObj.customerPoolName + "</option>";
                $("#customerPoolIdSelect1").html("<option value=''>请选择客户池名称</option>" + customerPoolOptionStr);
            }
            // 刷新下拉框
            $("#customerPoolIdSelect1").selectpicker('refresh');
        }
    });
}

// 上传图片
function uploadImg() {
    $(document).on('click', '.file-browser', function () {
        var file = $(this).closest('.file-group').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-group [type="file"]', function () {
        var $this = $(this);
        var $input = $(this)[0];
        var $len = $input.files.length;
        //var formFile = new FormData();
        if ($len == 0) {
            $input.nextElementSibling.value = '';
            $input.nextElementSibling.nextElementSibling.innerHTML = '';
            return;
        } else {
            var fileAccaccept = $this.attr('accaccept');
            var fileType = $input.files[0].type;
            var type = (fileType.substr(fileType.lastIndexOf("/") + 1)).toLowerCase();

            if (!type || fileAccaccept.indexOf(type) == -1) {
                lightyear.notify('您上传图片的类型不符合(' + fileAccaccept + ')', 'danger', 1500);
                $input.value = '';
                if ($input.nextElementSibling.value == '') {
                    $input.nextElementSibling.nextElementSibling.innerHTML = '';
                }
                return;
            } else {
                $input.nextElementSibling.value = '';
                var str = "<img src='" + getObjectURL(document.getElementById("customerPic1").files[0]) + "'/>";
                //将图片动态添加到图片展示区
                document.getElementById("customerImgBox").innerHTML = str;
            }
        }
    });
}

//获取图片路径方法
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}


/*
* 客户点击切换
* */
function changeTab(type) {
    if(type=='personal'){
        $(".personal").show()
        $(".enterprise").hide()
    }else{
        $(".personal").hide()
        $(".enterprise").show()
    }
}
//
// function setIframeHeight(iframe) {
//     if (iframe) {
//         var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
//         console.log(iframeWin , iframeWin.document.body ,iframeWin.document.documentElement.scrollHeight,iframeWin.document.body.scrollHeight)
//         if (iframeWin.document.body) {
//             iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
//         }
//     }
// };
//
// window.onload = function () {
//     setIframeHeight(document.getElementById('external-frame'));
// };
// function setHeight(el) {
//     console.log(el.contentWindow.document.body.offsetHeight,'el.contentWindow.document.body.offsetHeight')
//     el.style.height = '1700px'
// }